﻿using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.DependencyInjection;
using MockSchoolManagement.Core;
using MockSchoolManagement.Domain.Students;
using System;
using System.Linq;

namespace MockSchoolManagement.EntityFrameworkCore.Seed
{
    public static class DataInitializer
    {
        public static IApplicationBuilder UseDataInitializer(this IApplicationBuilder builder)
        {
            using (var scope=builder.ApplicationServices.CreateScope())
            {
                var dbcontext = scope.ServiceProvider.GetService<AppDbContext>();
                var userManager = scope.ServiceProvider.GetService<UserManager<ApplicationUser>>();
                var roleManager = scope.ServiceProvider.GetService<RoleManager<IdentityRole>>();

                #region 学生种子数据

                if (!dbcontext.Students.Any())
                {
                    var students = new[]
                    {
                        new Student(){Name = "张三",Email = "abc@qq.com",EnrollmentDate = DateTime.Now,PhotoPath = ""},
                        new Student(){Name = "李四",Email = "lisi@qq.com",EnrollmentDate = DateTime.Now,PhotoPath = ""},
                        new Student(){Name = "王五",Email = "wangwu@qq.com",EnrollmentDate = DateTime.Now,PhotoPath = ""},
                    };

                    foreach (var student in students)
                    {
                        dbcontext.Students.Add(student);
                    }

                    dbcontext.SaveChanges();
                }
                #endregion

                #region 用户种子数据

                if (!dbcontext.Users.Any())
                {
                    var user = new ApplicationUser()
                        {Email = "123@qq.com", UserName = "123@qq.com", EmailConfirmed = true, City = "新余"};
                    userManager.CreateAsync(user,"123456").Wait();
                    dbcontext.SaveChanges();
                    var adminRole = "Admin";
                    var role = new IdentityRole(adminRole);
                    dbcontext.Roles.Add(role);
                    dbcontext.SaveChanges();

                    dbcontext.UserRoles.Add(new IdentityUserRole<string>()
                    {
                        RoleId = role.Id,
                        UserId = user.Id
                    });
                    dbcontext.SaveChanges();
                }

                #endregion

                return builder;
            }
        }
    }
}
